package cn.xshi.scms.collect;

import cn.xshi.scms.model.SCMSMonitorMem;
import cn.xshi.scms.util.SigarUtil;
import cn.xshi.scms.model.SCMSMonitor;
import cn.xshi.scms.model.SCMSMonitorCpu;
import cn.xshi.scms.util.OSUtil;
import lombok.extern.slf4j.Slf4j;
import org.hyperic.sigar.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
/**
 * @Desc 服务器信息监控
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
@Order(1)
public class SCMSEvent implements CommandLineRunner {

//
//    @Scheduled(cron="*/30 * * * * *")
//    public void execute() {
//    }

    @Autowired
    RmiProxyFactoryBean rmiProxyFactoryBean;

    @Override
    public void run(String... args) throws Exception {
        new Thread(new SCMSEventWorker()).start();
    }

    /**
     *
     */
    class SCMSEventWorker implements Runnable{
        public void run(){
            while (true){
                try {
                    try {
                        SCMSMonitor scmsMonitor = monitor();
                        scmsMonitor.setScmsMonitorMem(memory());
                        scmsMonitor.setScmsMonitorCpus(cpu());
                        SCMSMonitorService scmsMonitorService = (SCMSMonitorService)rmiProxyFactoryBean.getObject();
                        scmsMonitorService.receiveSCMSMonitor(scmsMonitor);
                    } catch (Exception e) {
                        log.error("采集服务器信息异常1：{}",e);
                    }
                }catch (Exception e){
                    log.error("采集服务器信息异常2：{}",e);
                }finally {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * 主服务器监控
     */
    public SCMSMonitor monitor(){
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        InetAddress addr;
        SCMSMonitor scmsMonitor = new SCMSMonitor();
        try {
            Date date = new Date();
            addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress();
            Map<String, String> map = System.getenv();
            String userName = map.get("USERNAME");//获取用户名
            String computerName = map.get("COMPUTERNAME");//获取计算机名
            scmsMonitor.setUserName(userName);
            scmsMonitor.setAccountName(props.getProperty("user.name"));
            scmsMonitor.setComName(computerName);
            scmsMonitor.setLocalName(addr.getHostName());
            scmsMonitor.setJvmTotalMem(Integer.parseInt(""+r.totalMemory()));
            scmsMonitor.setJvmMem(Integer.parseInt(""+r.freeMemory()));
            scmsMonitor.setOperateSysName(props.getProperty("os.name"));
            scmsMonitor.setOperateOrg(props.getProperty("os.arch"));
            scmsMonitor.setJvmCpuCount(r.availableProcessors());
            scmsMonitor.setIp(ip);
            scmsMonitor.setEnvironment(props.getProperty("java.version"));
            scmsMonitor.setPath(props.getProperty("java.home"));
            scmsMonitor.setCreateTime(date);
            scmsMonitor.setUpdateTime(date);
            scmsMonitor.setMac(OSUtil.getMacAddress());
        } catch (UnknownHostException e) {
            log.error("主服务器信息获取失败{}",e);
        }
        return scmsMonitor;
    }

    /**
     * 内存监控
     * @return
     */
    public SCMSMonitorMem memory(){
        Mem mem;
        SCMSMonitorMem scmsMonitorMem = new SCMSMonitorMem();
        try {
            mem = SigarUtil.getMemory();
            Swap swap = SigarUtil.getSwap();
            scmsMonitorMem.setMemTotal(""+mem.getTotal() / 1024L);
            scmsMonitorMem.setMemCurrUse(""+mem.getUsed() / 1024L);
            scmsMonitorMem.setMemCurrSy(""+mem.getFree() / 1024L);
            scmsMonitorMem.setMemJhTotal(""+swap.getTotal() / 1024L);
            scmsMonitorMem.setMemJhCurrUse(""+swap.getUsed() / 1024L);
            scmsMonitorMem.setMemJhSy(""+swap.getFree() / 1024L);
            scmsMonitorMem.setCreateTime(new Date());
        } catch (SigarException e) {
            log.error("内存监控失败{}",e);
        }
        return scmsMonitorMem;
    }

    /**
     * CPU监控
     */
    public List<SCMSMonitorCpu> cpu(){
        List<SCMSMonitorCpu> scmsMonitorCpuList = new ArrayList<>();
        String libs = System.getProperty("java.library.path");
        System.setProperty("java.library.path", libs);
        try {
            CpuInfo[] cpuInfoList = SigarUtil.getCpuInfoList();
            CpuPerc cpu  = SigarUtil.getCpu();
            for(int i = 0; i < cpuInfoList.length; i++) {
                SCMSMonitorCpu scmsMonitorCpu = new SCMSMonitorCpu();
                CpuInfo info = cpuInfoList[i];
                scmsMonitorCpu.setCpuTotalMhz(info.getMhz());
                scmsMonitorCpu.setCpuProducer(info.getVendor());
                scmsMonitorCpu.setCpuCache(info.getCacheSize());
                /*scmsMonitorCpu.setCpuUserUseRate(CpuPerc.format(cpu.getUser()));
                scmsMonitorCpu.setCpuSysUseRate(CpuPerc.format(cpu.getSys()));
                scmsMonitorCpu.setCpuWaitUseRate(CpuPerc.format(cpu.getWait()));
                scmsMonitorCpu.setCpuErrorUseRate(CpuPerc.format(cpu.getNice()));
                scmsMonitorCpu.setCpuCurrentlyIdle(CpuPerc.format(cpu.getIdle()));
                scmsMonitorCpu.setCpuUseRate(CpuPerc.format(cpu.getCombined()));*/
                scmsMonitorCpu.setCpuUserUseRate(""+cpu.getUser());
                scmsMonitorCpu.setCpuSysUseRate(""+cpu.getSys());
                scmsMonitorCpu.setCpuWaitUseRate(""+cpu.getWait());
                scmsMonitorCpu.setCpuErrorUseRate(""+cpu.getNice());
                scmsMonitorCpu.setCpuCurrentlyIdle(""+cpu.getIdle());
                scmsMonitorCpu.setCpuUseRate(""+cpu.getCombined());
                scmsMonitorCpu.setNum(i+1);
                scmsMonitorCpu.setCreateTime(new Date());
                scmsMonitorCpuList.add(scmsMonitorCpu);
            }
        } catch (SigarException e) {
            log.error("内存监控失败{}",e);
        }
        return scmsMonitorCpuList;
    }
}
